package com.shkco.service.impl;

import com.shkco.domain.MovieTicket;
import com.shkco.domain.User;
import com.shkco.dto.MovieTicketDto;
import com.shkco.feign.UserService;
import com.shkco.mapper.MovieTicketMapper;
import com.shkco.result.JSONResult;
import com.shkco.service.IMovieTicketService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;

@Service
public class MovieTicketServiceImpl implements IMovieTicketService {

    @Autowired
    private MovieTicketMapper movieTicketMapper;

    @Autowired
    private UserService userService;

    @Override
    public List<MovieTicket> findAll() {
        return movieTicketMapper.findAll();
    }

    @Override
    public MovieTicket findById(Long id) {
        return movieTicketMapper.findById(id);
    }

    @Override
    public void update(MovieTicket movieTicket) {
        movieTicketMapper.update(movieTicket);
    }

    @Override
    public JSONResult buyMovie(MovieTicketDto movieTicketDto) {
        Long movieTicketId = movieTicketDto.getMovieTicketId();
        Long userId = movieTicketDto.getUserId();
        MovieTicket movieTicket = movieTicketMapper.findById(movieTicketId);
        User user = userService.findById(userId);
        if (user != null){
            BigDecimal price = movieTicket.getPrice();
            BigDecimal balance = user.getBalance();
            if (balance.compareTo(price) == 1){
                BigDecimal bigDecimal = balance.subtract(price);
                User user1 = new User();
                user1.setBalance(bigDecimal);
                Integer stock = movieTicket.getStock();
                if (stock > 0) {
                    Integer remain = (stock - 1);
                    movieTicket.setStock(remain);
                    MovieTicketDto userMovieId = movieTicketMapper.findUserMovieId(movieTicketDto);
                    if (userMovieId!= null){
                        Integer count = userMovieId.getCount() + 1;
                        movieTicketDto.setCount(count);
                        movieTicketMapper.userMovieUpdate(movieTicketDto);
                    } else {
                        movieTicketMapper.add(movieTicketDto);
                    }
                    movieTicketMapper.update(movieTicket);
                    user1.setId(movieTicketDto.getUserId());
                    userService.update(user1);
                    return JSONResult.success("购票成功");
                }
                return JSONResult.error("购票失败，电影票已经售罄");
            }
            return JSONResult.error("余额不足！购票失败！");
        }
        return JSONResult.error("购票失败");

    }
}
